package co.fitstart.admin.web.controller.course;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.cache.accessor.PersistentAccessor;
import co.fitstart.admin.service.CourseRoundService;
import co.fitstart.admin.service.DataService;
import co.fitstart.admin.service.GroupService;
import co.fitstart.admin.service.GroupTemplateService;
import co.fitstart.admin.service.OnlineRoundService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.course.round.CourseRoundGroup;
import co.fitstart.entity.course.round.CourseRoundResource;
import co.fitstart.entity.courseware.CoursewareTag;
import co.fitstart.entity.courseware.FitnessTag;
import co.fitstart.entity.courseware.fitnessgroup.FitnessGroup;
import co.fitstart.entity.order.OrderInvestigateRecord;

/**
 * 
 * @author lidan
 * @author mohanlan
 */
@Controller
@RequestMapping("/online-rounds")
@MenuSetting("menu-course")
public class OnlineRoundEditController {
    
    private static final Logger logger = LoggerFactory.getLogger(OnlineRoundEditController.class);
    
    @Autowired
    private OnlineRoundService onlineRoundService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<CourseRoundResource> dataService;
    
    @Autowired
    private CourseRoundService courseRoundService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<CourseRoundGroup> courseRoundGroupService;
    
    @Autowired
    private GroupTemplateService groupTemplateService;
    
    @Autowired
    private GroupService groupService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<FitnessTag> fitnessTagService;
    
    @Autowired
    private PersistentAccessor persistentAccessor;
    
    @Value("#{config['file.upload.path']}")
    private String uploadPath;
    
    
    /**
     * View online round
     * 
     * @param roundCode
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "/{roundCode}" , method = RequestMethod.GET, params = "grouped=false")
    @MenuSetting("submenu-online-course-arrange")
    public ModelAndView view(@PathVariable("roundCode") String roundCode,
                             Page page,
                             HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("course/online/view/online-round-view");
        
        List<CourseRound> courseRounds = onlineRoundService.list(roundCode, page);
        
        modelAndView.addObject("courseRounds", courseRounds);
        
        CourseRoundResource courseRoundResource = onlineRoundService.loadCourseRoundResource(roundCode);
        modelAndView.addObject("courseRoundResource", courseRoundResource);
        
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "view");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
        
    }
    
    /**
     * View online round by group
     * 
     * @param roundCode
     * @param courseRoundGroupId
     * @param finished
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "/{roundCode}" , method = RequestMethod.GET, params = "grouped=true")
    @MenuSetting("submenu-online-course-arrange")
    public ModelAndView viewByGroup(@PathVariable("roundCode") String roundCode,
                             @RequestParam(value = "group", required = false) String groupName,
                             Page page,
                             HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("course/online/view/online-round-view");
        
        List<CourseRound> courseRounds = new ArrayList<CourseRound>();
        
        if (groupName == null) {
            courseRounds = onlineRoundService.listUnfinishCourseRound(roundCode, page);
        }else {
            courseRounds = onlineRoundService.listFinishRoundByGroup(roundCode, groupName, page);
        }
        modelAndView.addObject("courseRounds", courseRounds);
        
        CourseRoundResource courseRoundResource = onlineRoundService.loadCourseRoundResource(roundCode);
        modelAndView.addObject("courseRoundResource", courseRoundResource);
        
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "view");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    
    /**
     * view courseRoundId change group
     * 
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}", method = RequestMethod.GET)
    @MenuSetting("submenu-online-course-arrange")
    public ModelAndView studentView(@PathVariable("roundCode") String roundCode , @PathVariable("roundId") Long roundId) {
        
        ModelAndView modelAndView = new ModelAndView("course/online/view/online-round-student-view");
        
        CourseRound courseRound = onlineRoundService.loadCourseRound(roundId);
        modelAndView.addObject("courseRound", courseRound);
        
        OrderInvestigateRecord orderInvestigateRecord = persistentAccessor.orderInvestigationRecord(courseRound.getOrder());
        modelAndView.addObject("investigate", orderInvestigateRecord);
        
        return modelAndView;
    }
    
    /**
     * view courseRoundId change group
     * 
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}/courseware", method = RequestMethod.GET)
    @MenuSetting("submenu-online-course-arrange")
    public ModelAndView CourseWareview(@PathVariable("roundCode") String roundCode , @PathVariable("roundId") Long roundId) {
        
        ModelAndView modelAndView = new ModelAndView("course/online/view/online-round-courseware-view");
        
        return modelAndView;
    }
    
    /**
     * Investigation view page
     * 
     * @param orderId
     * @param orderType 
     * @return
     */
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}/investigate", method = RequestMethod.GET)
    @MenuSetting("submenu-online-course-arrange")
    public ModelAndView investigation(@PathVariable("roundCode") String roundCode,
    		                          @PathVariable("roundId") Long roundId,
                                      @RequestParam("investigateType") String investigateType){
        
        ModelAndView modelAndView = new ModelAndView("course/online/view/online-" + investigateType + "-investigate-view");
        
        CourseRound courseRound = onlineRoundService.loadCourseRound(roundId);
        OrderInvestigateRecord orderInvestigateRecord = persistentAccessor.orderInvestigationRecord(courseRound.getOrder());
        
        modelAndView.addObject("investigate", orderInvestigateRecord);
        
        return modelAndView;
    }
    
    
    /**
     * Display edit remarks
     * 
     * @param roundCode
     * @param roundId
     * @return
     */
    @RequestMapping(value = "/{roundCode}/group", method = RequestMethod.GET)
    public ModelAndView group(@PathVariable("roundCode") String roundCode){
        
        ModelAndView modelAndView = new ModelAndView("course/online/online-round-group");
        
        modelAndView.addObject("roundCode", roundCode);
        
        return modelAndView;
        
    }
    
    /**
     * Do edit remarks
     * 
     * @param roundCode
     * @param roundId
     * @param remarks
     * @return
     */
    @RequestMapping(value = "/{roundCode}/group", method = RequestMethod.PATCH)
    public @ResponseBody String onGroup(@PathVariable("roundCode") String roundCode){
        
        Result result = new Result();
        
        try{
            
            onlineRoundService.group(roundCode);
            
            result.success().message("线上课程分组成功");
            
        }catch(Exception e){
            
            logger.error("onGroup() error", e);
            
            result.fail().message("线上课程分组失败");
            
        }
        
        return JsonUtils.toJsonString(result);
        
    }
    
    /**
     * 
     * @param roundCode
     * @param roundId
     * @return
     */
    @RequestMapping(value = "/{roundCode}/batch-change-group", method = RequestMethod.GET)
    public ModelAndView batchChangeGroup(@PathVariable("roundCode") String roundCode) {
        
        ModelAndView modelAndView = new ModelAndView("course/online/online-round-batch-change-group");
        
        modelAndView.addObject("roundCode", roundCode);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param roundId
     * @param groupId
     * @param tagIds
     * @return
     */
    @RequestMapping(value = "/{roundCode}/batch-change-group", method = RequestMethod.PATCH)
    public @ResponseBody String onBatchChangeGroup(@PathVariable("roundCode") String roundCode,
                                                   @RequestParam("groupId") Long groupId,
                                                   @RequestParam(value = "tagIds", required = false) String tagIds,
                                                   @RequestParam(value = "groupName", required = false) String groupName){
        Result result = new Result();
        
        try {
            
            FitnessGroup fitnessGroup = groupTemplateService.loadFitnessGroup(groupId);
            
            courseRoundService.batchChangeGroup(roundCode, groupName, fitnessGroup, tagIds);
            
            result.success().message("批量分组成功");
            
        } catch (Exception e) {
            
            result.fail().message("批量分组失败");
            
            logger.error("#onChangeGroup() error ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param roundCode
     * @param roundId
     * @return
     */
    @RequestMapping(value = "/{roundCode}/batch-link", method = RequestMethod.GET)
    public ModelAndView batchLink(@PathVariable("roundCode") String roundCode,
                                  @RequestParam(value = "groupName", required = false) String groupName) {
        
        ModelAndView modelAndView = new ModelAndView("course/online/online-round-batch-link");
        
        modelAndView.addObject("roundCode", roundCode);
        modelAndView.addObject("groupName", groupName);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param roundId
     * @param groupId
     * @param tagIds
     * @return
     */
    @RequestMapping(value = "/{roundCode}/batch-link", method = RequestMethod.PATCH)
    public @ResponseBody String onBatchLink(@PathVariable("roundCode") String roundCode,
                                            @RequestParam(value = "groupName", required = false) String groupName,
                                            @RequestParam("week") int week,
                                            @RequestParam("coachTips") String coachTips){
        Result result = new Result();
        
        try {
            
            groupService.onlineRoundBatchLink(roundCode, groupName, week, coachTips);
            
            result.success().message("批量发送课件成功");
            
        } catch (Exception e) {
            
            result.fail().message("批量发送课件失败");
            
            logger.error("#onBatchLink() error ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param roundCode
     * @param roundId
     * @return
     */
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}/change-group", method = RequestMethod.GET)
    public ModelAndView changeGroup(@PathVariable("roundCode") String roundCode,
                                    @PathVariable("roundId") Long roundId) {
        
        ModelAndView modelAndView = new ModelAndView("course/online/online-round-change-group");
        
        CourseRound courseRound = courseRoundService.loadCourseRound(roundId);
        
        modelAndView.addObject("courseRound", courseRound);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param roundId
     * @param groupId
     * @param tagIds
     * @return
     */
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}/change-group", method = RequestMethod.PATCH)
    public @ResponseBody String onChangeGroup(@PathVariable("roundId") Long roundId,
                                              @RequestParam("groupId") Long groupId,
                                              @RequestParam(value = "tagIds", required = false) String tagIds){
        Result result = new Result();
        
        try {
            
            CourseRound courseRound = onlineRoundService.loadCourseRound(roundId);
            FitnessGroup fitnessGroup = groupTemplateService.loadFitnessGroup(groupId);
            
            courseRoundService.changeGroup(courseRound, fitnessGroup, tagIds);
            
            result.success().message("更改分组成功");
            
        } catch (Exception e) {
            
            result.fail().message("更改分组失败");
            
            logger.error("#onChangeGroup() error ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param roundCode
     * @param roundId
     * @return
     */
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}/edit-group", method = RequestMethod.GET)
    public ModelAndView editGroup(@PathVariable("roundCode") String roundCode,
                                  @PathVariable("roundId") Long roundId) {
        
        ModelAndView modelAndView = new ModelAndView("course/online/online-round-edit-group");
        
        CourseRound courseRound = onlineRoundService.loadCourseRound(roundId);
        modelAndView.addObject("courseRound", courseRound);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param roundId
     * @param groupId
     * @return
     */
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}/edit-group", method = RequestMethod.PATCH)
    public @ResponseBody String onEditGroup(@PathVariable("roundId") Long roundId,
                                              @RequestParam("groupId") Long groupId){
        Result result = new Result();
        
        try {
            
            CourseRound courseRound = onlineRoundService.loadCourseRound(roundId);
            FitnessGroup fitnessGroup = groupTemplateService.loadFitnessGroup(groupId);
            
            courseRoundService.editGroup(courseRound, fitnessGroup);
            
            result.success().message("更改分组成功");
            
        } catch (Exception e) {
            
            result.fail().message("更改分组失败");
            
            logger.error("#onChangeGroup() error ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param roundCode
     * @param roundId
     * @return
     */
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}/edit-tag", method = RequestMethod.GET)
    public ModelAndView editTag(@PathVariable("roundCode") String roundCode , @PathVariable("roundId") Long roundId) {
        
        ModelAndView modelAndView = new ModelAndView("course/online/online-round-tag");
        
        CourseRound courseRound = courseRoundService.loadCourseRound(roundId);
        List<CoursewareTag> coursewareTags = persistentAccessor.coursewareTags(courseRound.getStudent().getArrayTagIds());
        List<Long> fitnessTags = new ArrayList<Long>();
        if(coursewareTags != null && !coursewareTags.isEmpty()) {
            for(CoursewareTag coursewareTag : coursewareTags) {
                fitnessTags.add(coursewareTag.getFitnessTag().getId());
            }
        }
        
        modelAndView.addObject("fitnessTags", fitnessTags);
        
        modelAndView.addObject("roundCode", roundCode);
        modelAndView.addObject("roundId", roundId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param roundCode
     * @param roundId
     * @param tagIds
     * @return
     */
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}/edit-tag", method = RequestMethod.PATCH)
    public @ResponseBody String onEditTag(@PathVariable("roundCode") String roundCode ,
                                          @PathVariable("roundId") Long roundId,
                                          @RequestParam(value = "tagIds", required = false) String tagIds){
        Result result = new Result();
        
        try {
            CourseRound courseRound = courseRoundService.loadCourseRound(roundId);
            
            courseRoundService.editTag(courseRound, tagIds);
            
            result.success().message("添加标签成功");
            
        } catch (Exception e) {
            
            result.fail().message("添加标签失败");
            
            logger.error("#onTag() error ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}/transfer-class", method = RequestMethod.GET)
    public ModelAndView transferClass(@PathVariable("roundCode") String roundCode,
                                      @PathVariable("roundId") Long roundId) {
        
        ModelAndView modelAndView = new ModelAndView("course/online/online-round-transfer-class");
        
        CourseRound courseRound = onlineRoundService.loadCourseRound(roundId);
        
        CourseRoundGroup group = onlineRoundService.loadCourseRoundGroup(courseRound);
        
        modelAndView.addObject("courseRound", courseRound);
        modelAndView.addObject("group", group);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param roundCode
     * @param roundId
     * @param group
     * @return
     */
    @RequestMapping(value = "/{roundCode}/rounds/{roundId}/transfer-class", method = RequestMethod.PATCH)
    public @ResponseBody String onTransferClass(@PathVariable("roundCode") String roundCode ,
                                          @PathVariable("roundId") Long roundId,
                                          @RequestParam("group") String group){
        Result result = new Result();
        
        try {
            CourseRound courseRound = courseRoundService.loadCourseRound(roundId);
            
            onlineRoundService.editCourseRoundGroup(courseRound, group);
            
            result.success().message("转班成功");
            
        } catch (Exception e) {
            
            result.fail().message("转班失败");
            
            logger.error("#onTransferClass() error ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
}
